/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState } from 'react';
import { Row, Col, Popconfirm, Button, Empty, Table, message, Modal } from 'antd';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { copy } from '@/utils/utils';
import { useDispatch, useSelector } from 'dva';
import router from 'umi/router';
import styles from './WorkOrder.less';

const columns = [
  {
    title: '',
    dataIndex: 'num',
    key: 'num',
  },
  {
    title: '角色',
    dataIndex: 'roles',
    key: 'roles',
  },
  {
    title: '说明',
    dataIndex: 'info',
    key: 'info',
    // align: "left",
  },
];

const dataSource = [
  {
    num: 1,
    roles: '超级管理员',
    info: '拥有所有工单系统所有权限，快宝智慧快递管理平台注册用户',
  },
  {
    num: 2,
    roles: '客服',
    info:
      '由管理员设置，从现有业务中选择，专门处理客诉的专职客服，拥有在工单系统、快递员APP（移动版工单处理软件),创建/分配/处理/关闭/打回/重启/查看工单的权限',
  },
  {
    num: 3,
    roles: '快递员',
    info:
      '来源于基础数据——业务员，本职工作为快递员身份的成员，拥有在工单系统、快递员APP（移动版工单处理软件)，有创建/分配/处理/查看工单的权限',
  },
  {
    num: 4,
    roles: '驿站',
    info:
      '来源于管理平台添加的驿站，本职为驿站身份的成员，拥有在工单系统、驿站APP，有创建/分配/处理/查看工单的权限',
  },
];

const WorkOrder = () => {
  const { shop_id: shopId, user_info: userInfo = {} } = useSelector(
    ({ user: { currentUser } = {} }) => currentUser,
  );
  const { key } = useSelector(({ setting = {} }) => setting.options);
  const { openStatus } = useSelector(({ workOrder }) => workOrder);
  const dispatch = useDispatch();

  const [registered, setRegistered] = useState(false);

  const { phone: adminPhone } = userInfo;

  const onCopyClick = text => {
    copy(text, copied => {
      if (copied) {
        message.success('复制成功！');
      } else {
        message.warning('复制失败，请手动复制！');
      }
    });
  };

  const onJump = () => {
    dispatch({
      type: 'workOrder/getLoginToken',
      payload: {
        id: shopId,
        type: 1,
      },
    })
      .then(token => {
        if (token) {
          window.open(`http://feedback.kuaidihelp.com/user/login?token=${token}`);
        } else {
          message.error('获取token失败，无法登录');
        }
      })
      .catch();
  };

  const onConfirm = status => {
    dispatch({
      type: 'workOrder/changeOpenStatus',
      payload: { shop_id: shopId, operate: status ? 'close' : 'open' },
    })
      .then(isRegistered => {
        setRegistered(isRegistered);
        if (!status && !isRegistered) {
          Modal.info({
            title: '温馨提示',
            okText: '我已知晓',
            content: isRegistered
              ? '管理员已注册快递员app，可使用快递员app在工单系统登录界面直接扫码登录'
              : `您账号${adminPhone}尚未注册快递员app或不在此快宝智慧快递管理平台中，注册快递员后，在快宝智慧快递管理平台——基础数据——业务员-添加业务员，将此账号添加进去后，可使用快递员app在工单系统登录界面直接扫码登录。`,
          });
        } else {
          message.success(status ? '关闭成功' : '开启成功');
        }
        dispatch({
          type: 'workOrder/checkOpened',
          payload: { shop_id: shopId },
        });
      })
      .catch(() => {});
  };

  useEffect(
    () => {
      if (key == 'post') {
        router.replace('/');
        return;
      }
      dispatch({
        type: 'workOrder/checkOpened',
        payload: { shop_id: shopId },
      });
    },
    [dispatch, shopId, key],
  );

  return (
    <PageHeaderLayout
      title="工单系统"
      content={
        <Row type="flex" justify="space-between" align="middle">
          <Col>
            旗下业务员、驿站、和您在工单系统_成员设置中添加的客服，可在工单系统创建、分配、处理、完结，查看相关工单
            <a href="https://m.kuaidihelp.com/help/feed_back_help" target="_blank" rel="noreferrer">
              点此了解更多
            </a>
          </Col>
          <Col>
            <Popconfirm
              title={`确认${openStatus ? '关闭' : '开启'}？`}
              onConfirm={() => onConfirm(openStatus)}
            >
              <Button type="primary">{openStatus ? '关闭' : '开启'}</Button>
            </Popconfirm>
          </Col>
        </Row>
      }
    >
      <div className={styles.main}>
        {openStatus ? (
          <div>
            <Row gutter={[0, 20]}>
              <Col>
                旗下业务员、驿站、客服，可通过此网址登录工单系统（需使用快递员APP
                9.0、快宝驿站APP5.4及以上版本使用工单系统）
              </Col>
              <Col>
                <Row type="flex" align="middle" gutter={[20, 0]}>
                  <Col style={{ fontWeight: 'bold' }}>
                    工单系统地址：http://feedback.kuaidihelp.com
                  </Col>
                  <Col>
                    <Button
                      type="primary"
                      onClick={() => onCopyClick('http://feedback.kuaidihelp.com')}
                    >
                      复制网址
                    </Button>
                  </Col>
                  <Col>
                    <Button type="primary" onClick={onJump}>
                      点击前往
                    </Button>
                  </Col>
                </Row>
              </Col>
              {registered ? (
                <Col>管理员已注册快递员app，可使用快递员app在工单系统登录界面直接扫码登录</Col>
              ) : null}
            </Row>
            <Table
              style={{ marginTop: 20 }}
              rowKey="num"
              dataSource={dataSource}
              columns={columns}
              pagination={false}
            />
          </div>
        ) : (
          <Empty description="暂未开启工单系统" />
        )}
      </div>
    </PageHeaderLayout>
  );
};

export default WorkOrder;
